<?php
set_time_limit(0);

include_once('lib/config.php');
include_once('lib/Db.class.php');
include_once('lib/Model.class.php');
include_once('lib/Upyun.class.php');
include_once('lib/function.php');

$redis = new Redis();
$redis->connect(REDIS_IP,"6379");  //php客户端设置的ip及端口
if(!$redis) die('redis connect fail');

$model = new Model;
$localDir = dirname(__FILE__).'/Public';
$upyun = new UpYun(UPYUN_BUCKET_LPN, UPYUN_USER, UPYUN_PASS);

$limit = 100;
while($limit--) {
  $stop = $redis->get('LNPAN_QUEUE_STOP');
  if($stop) {
    break;
  }

  $url = $redis->lPop(KEY_QUEUE_TO_UPLOAD);
  if(!$url) {
    sleep(1);
    continue;
  }

  $parse = parse_url($url);
  $filename = $localDir.$parse['path'];
  try {
    $upfile = '/music'.$parse['path'];
    $fh = fopen($filename, 'rb');
    $rsp = $upyun->writeFile($upfile, $fh, True); //上传图片，自动创建目录
    fclose($fh);
    if($rsp) {
      $filesize = filesize($filename);
      $filesize = intval($filesize / 1024).'KB';
      $model->query("update ring_news_format set state=3,format_upyun='".$upfile."',format_size='".$filesize."' where state=1 and format_url='".$url."'");
      
      $news_format = $model->find('ring_news_format', "format_url='".$url."'");
      if($news_format) {
        $news = $model->find('ring_news', "id='".$news_format['news_id']."'");
        if($news) {
          $down_info = json_decode($news['down_info'], true);
          foreach ($down_info as &$item) {
            if($item['down_url'] == $url) {
              $item['size'] = $filesize;
            }
          }
         
          $update_data['down_info'] = json_encode($down_info);
          $model->save('ring_news', "id='$news[id]'", $update_data);
        }
      }

      $redis->lPush(KEY_QUEUE_LOCAL_UPLOAD_SUCCESS, date('Y-m-d H:i:s') .':http://dl.lnpan.com'.$upfile);
    } else {
      $redis->lPush(KEY_QUEUE_LOCAL_UPLOAD_FAIL, date('Y-m-d H:i:s') .':'.$rsp);
      $redis->rPush(KEY_QUEUE_TO_UPLOAD, $url);
    }
  }
  catch(Exception $e) {
    $error = $e->getCode().':'.$e->getMessage();
    $redis->lPush(KEY_QUEUE_LOCAL_UPLOAD_FAIL, date('Y-m-d H:i:s') .':'.$error);
    $redis->rPush(KEY_QUEUE_TO_UPLOAD, $url);
  } 

  //break;
}
